import React, { useEffect, useRef, useState } from 'react'
import Category from '@/components/Category'
import {
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  LoadingOutlined,
  EditFilled,
} from '@ant-design/icons'
import { cloneDeep } from 'lodash'
// 当前bug&&warning
// 三级列表的initialValues改写错误
// 刷新页面时偶尔出现的redux错误
import {
  Button,
  Card,
  Form,
  Input,
  InputRef,
  message,
  Popconfirm,
  Table,
  Tag,
} from 'antd'
import {
  addAttrsItem,
  AttrsItemType,
  AttrValueItemType,
  AttrValueListType,
  deleteAttr,
  getAttrsList,
} from '@/api/Product/attrs'
import { store } from '@/app/store'
import { category1id, category2id, category3id } from '@/app/category'
import { ColumnsType } from 'antd/lib/table'
import FormItem from 'antd/lib/form/FormItem'
import { nanoid } from 'nanoid'
import form from 'antd/lib/form'
function Attr() {
  const [lazy, setlazy] = useState({})
  // 交替显示list与add卡片
  const [isShowit, setIsShowit] = useState(false)
  const categoryStore = store.getState()
  const reqAttrlist = async function () {
    setloading(true)
    let re = await getAttrsList(
      category1id(categoryStore) as number,
      category2id(categoryStore) as number,
      category3id(categoryStore) as number
    )
    setloading(false)
    setTableDate(re)
  }
  // 用于复写的id
  const [reId, setReId] = useState<number | undefined>(undefined)
  // 表单
  const [TableForm] = form.useForm()
  // 表单数据的变量显示用于规范按钮
  const AttrName = Form.useWatch('AttrName', TableForm)
  // loading
  const [loading, setloading] = useState(false)
  // INPUT的ref
  const WriteInput = useRef<InputRef>(null)
  // 展开添加页面
  const openAdd = function () {
    //数据初始化
    setReId(undefined)
    setValueList([])
    TableForm.setFieldsValue({
      AttrName: '',
    })
    setIsShowit(true)
  }
  // 关闭
  const closeAdd = function () {
    setIsShowit(false)
  }
  // 新增属性值数据
  const addValueItem = function () {
    // 表格中的数组需要添加响应式就需要使用替换数组的方式,否则没有响应式
    ValueList.push({
      valueName: '',
      isShow: false,
      Nanoid: nanoid(),
    })
    setValueList([...ValueList])
    setTimeout(() => {
      WriteInput.current?.focus()
    })
  }
  // 切换为书写模式
  const changeWrite = function (row: AttrValueItemType) {
    return () => {
      row.isShow = false
      TableForm.setFieldsValue({
        [(row.id ? row.id : row.Nanoid) as string]: row.valueName,
      })
      // 获取焦点
      setTimeout(() => {
        WriteInput.current?.focus()
      })
      // 强制刷新页面
      setlazy({})
    }
  }
  // input移出后的回调
  const inputBlur = function (row: AttrValueItemType, index: number) {
    return () => {
      row.valueName = TableForm.getFieldValue(
        row.id ? row.id : (row.Nanoid as string)
      )
      // 重复判断
      let lengList = ValueList.filter(
        (item) => item.valueName === row.valueName
      )
      // 非空判断
      if (!row.valueName || lengList.length > 1) {
        ValueList.splice(index, 1)
        setValueList([...ValueList])
      }

      row.isShow = true
      // 强制刷新页面
      setlazy({})
    }
  }
  // 发送请求
  const save = async function () {
    const attrName = TableForm.getFieldValue('AttrName')
    let attrinfo = {
      id: reId,
      attrName,
      attrValueList: ValueList,
      categoryId: category3id(categoryStore) as number,
      categoryLevel: 3,
    }
    await addAttrsItem(attrinfo)
    message.success('数据添加成功')
    reqAttrlist()
    setIsShowit(false)
  }
  // 删除单个属性值数据
  const delValueItem = function (index: number) {
    return () => {
      ValueList.splice(index, 1)
      setValueList([...ValueList])
    }
  }
  // 复写
  const reWaiteItem = function (row: AttrsItemType) {
    return () => {
      setReId(row.id as number)
      TableForm.setFieldsValue({
        AttrName: row.attrName,
      })
      let attrValueList = row.attrValueList.map((item): AttrValueItemType => {
        item.isShow = true
        return item
      })
      setValueList(cloneDeep(attrValueList))
      //打开新增页面
      setIsShowit(true)
    }
  }
  // 删除整个平台数据
  const removeAttrValueItem = function (id: number) {
    return async () => {
      await deleteAttr(id)
      //重新渲染页面
      reqAttrlist()
    }
  }

  // ---- 生成rowkey的函数
  const setKey = function (recode: AttrValueItemType) {
    return (recode.id ? recode.id : recode.Nanoid) as string
  }
  // 表格数据
  const [tableDate, setTableDate] = useState<AttrsItemType[]>([])
  const columns: ColumnsType<AttrsItemType> = [
    {
      title: '序号',
      width: 80,
      render: (_, __, index) => {
        return index + 1
      },
    },
    {
      title: '属性值名称',
      dataIndex: 'attrName',
      width: 120,
    },
    {
      title: '属性值列表',
      dataIndex: 'attrValueList',
      width: '60%',
      render: (item: AttrValueListType, row, index) => {
        return (
          <div key={row.id}>
            {item.map((el) => {
              return (
                <Tag color="green" key={el.id}>
                  {el.valueName}
                </Tag>
              )
            })}
          </div>
        )
      },
    },
    {
      title: '操作',
      render: (a, row, index) => {
        return (
          <div>
            <Button
              type="primary"
              icon={<EditFilled />}
              onClick={reWaiteItem(row)}
            />
            <Popconfirm
              title="确定删除吗"
              onConfirm={removeAttrValueItem(row.id as number)}
              okText="确定"
              style={{ marginLeft: 30 }}
              cancelText="取消"
            >
              <Button
                style={{ marginLeft: 30 }}
                type="primary"
                icon={<DeleteOutlined />}
                danger
              />
            </Popconfirm>
          </div>
        )
      },
    },
  ]
  // 属性值列表的数据
  const [ValueList, setValueList] = useState<AttrValueListType>([])
  // 属性值列表的column
  const valueListcloumns: ColumnsType<AttrValueItemType> = [
    {
      title: '序号',
      width: 80,
      render: (_, __, index) => {
        return index + 1
      },
    },
    {
      title: '属性值名称',
      dataIndex: 'valueName',
      render(item, row, index) {
        return (
          <div>
            <FormItem
              name={row.id ? row.id : row.Nanoid}
              wrapperCol={{ span: 5 }}
              hidden={row.isShow}
            >
              <Input ref={WriteInput} onBlur={inputBlur(row, index)} />
            </FormItem>
            <div onClick={changeWrite(row)} hidden={!row.isShow}>
              {row.valueName}
            </div>
          </div>
        )
      },
    },
    {
      title: '操作',
      render: (a, row, index) => {
        return (
          <div>
            <Button
              type="primary"
              shape="round"
              icon={<DeleteOutlined />}
              danger
              onClick={delValueItem(index)}
            />
          </div>
        )
      },
    },
  ]
  useEffect(() => {
    store.subscribe(() => {
      setlazy({})
    })
    if (category3id(categoryStore)) {
      reqAttrlist()
    }
  }, [categoryStore.category.category3id])
  return (
    <div>
      <Category disabled={isShowit}></Category>
      <Card hidden={isShowit}>
        <Button
          type="primary"
          onClick={openAdd}
          icon={<PlusOutlined />}
          disabled={!category3id(store.getState())}
        >
          添加属性
        </Button>
        <Table
          style={{ marginTop: 20 }}
          dataSource={tableDate}
          columns={columns}
          rowKey={'id'}
          pagination={false}
          loading={loading}
        ></Table>
      </Card>
      <Card hidden={!isShowit}>
        <Form form={TableForm}>
          <FormItem wrapperCol={{ span: 5 }} label="属性名" name={'AttrName'}>
            <Input placeholder="请输入属性名" />
          </FormItem>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={addValueItem}
            disabled={!AttrName}
          >
            添加属性值
          </Button>
          <Button onClick={closeAdd} type="default" style={{ marginLeft: 20 }}>
            取消
          </Button>
          <Table
            style={{ marginTop: 20, marginBottom: 20 }}
            columns={valueListcloumns}
            dataSource={ValueList}
            rowKey={setKey}
            pagination={false}
          ></Table>
        </Form>

        <Button type="primary" onClick={save} disabled={ValueList.length === 0}>
          保存
        </Button>
        <Button onClick={closeAdd} type="default" style={{ marginLeft: 20 }}>
          取消
        </Button>
      </Card>
    </div>
  )
}

export default Attr
